import Vue from 'vue'
import VueRouter from 'vue-router'
import {getToken} from '@/utils/auth'

import Login from '@/views/login'
import Layout from '@/layout/index.vue'
import {Page401, Page404} from '@/views/error-page'

import systemRoute from './modules/system'

Vue.use(VueRouter)

const routes = [
    {
        path: '/',
        name: 'home',
        component: Layout
    },
    {
        path: '/login',
        name: 'login',
        component: Login
    },
    {
        path: '/401',
        name: 'Page401',
        component: Page401
    },
    {
        path: '/404',
        name: 'Page404',
        component: Page404
    },
    ...systemRoute,
    {
        path: '*',
        redirect: '/404'
    }
]

const router = new VueRouter({
    mode: 'history',
    base: process.env.BASE_URL,
    routes
})

export default router

router.beforeEach((to, from, next) => {
    let token = getToken()
    if (token) {
        // 登录了
        if (to.path === '/login') {
            // 登录了，访问登录页就重定向到首页
            console.log('登录了，访问登录页就重定向到首页')
            next({path: '/'})
        } else {
            // todo 判断权限
            // 现在直接放行
            next()
        }
    } else {
        // 未登录
        if (to.path === '/login') {
            // 现在直接放行
            next()
        } else {
            // 未登录，重定向到登录页
            console.log('未登录，重定向到登录页')
            next({path: '/login', redirect: to.path})
        }
    }
})
